#!/bin/bash
## This was taken from http://netninja.com/2011/05/03/trunk-notes-lookups-from-the-desktop/
# slight mod made for my path
# I use this for my old Notational Velocity data.
# still need a good linux way to do nvAlt

if [ -z "$1" ]; then
    echo "Put search term on command line"
    exit 1
fi

# Set this to:
#  0 to only show matching notes
#  1 to show matches lines in context first, before printing matching notes
PRINT_MATCHES_IN_CONTEXT=0

# Find matches
LIST=/tmp/notelist.$$.txt
grep -r -i -l "$1" ~/Notes > $LIST
if [ $PRINT_MATCHES_IN_CONTEXT -eq 1 ]; then
    grep -r -i --color "$1" ~/Notes
    echo ""
fi

# Display list of matching files
exec<$LIST
COUNTER=1
echo "[0] abort"
while read LINE
do
    FILE=`basename "$LINE"`
    echo "[$COUNTER] $FILE"
    ((COUNTER=COUNTER + 1))
done

# Ask for selection
exec<&1
echo -n "Selection: "
read SELECTION

# Find file that matches selection and display it
exec<$LIST
COUNTER=1
while read LINE
do
    if [ "$COUNTER" == "$SELECTION" ]; then
        less -i -p "$1" "$LINE"
    fi
    ((COUNTER=COUNTER + 1))
done

# Clean up temp file
rm -f $LIST
